package cn.minhx.domain.activity.service.trial.node;

import cn.minhx.domain.activity.model.entity.MarketProductEntity;
import cn.minhx.domain.activity.model.entity.TrialBalanceEntity;
import cn.minhx.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import cn.minhx.domain.activity.service.trial.AbstractGroupBuyMarketSupport;
import cn.minhx.domain.activity.service.trial.factory.DefaultActivityStrategyFactory;
import cn.minhx.types.design.tree.StrategyHandler;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 人群标签
 *
 * @author min
 */
@Slf4j
@Service
public class CrowdNode extends AbstractGroupBuyMarketSupport {

	@Resource
	private EndNode endNode;

	@Override
	protected TrialBalanceEntity doApply(MarketProductEntity requestParameter,
			DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
		log.info("拼团商品查询试算服务-CrowdNode requestParameter:{}", JSON.toJSONString(requestParameter));
		// 获取拼团活动配置
		GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = dynamicContext.getGroupBuyActivityDiscountVO();
		String tagId = groupBuyActivityDiscountVO.getTagId();
		boolean visibleLimit = groupBuyActivityDiscountVO.isVisible();
		boolean enableLimit = groupBuyActivityDiscountVO.isEnable();
		// 人群标签配置为空，默认值
		if (StringUtils.isBlank(tagId)) {
			dynamicContext.setVisible(true);
			dynamicContext.setEnable(true);
			return router(requestParameter, dynamicContext);
		}
		// 是否在人群范围内；visible、enable 如果值为 ture 则表示没有配置拼团限制，那么就直接保证为 true 即可
		boolean isWithin = repository.withinCrowdTag(tagId, requestParameter.getUserId());
		dynamicContext.setVisible(visibleLimit || isWithin);
		dynamicContext.setEnable(enableLimit || isWithin);
		return router(requestParameter, dynamicContext);
	}

	@Override
	public StrategyHandler<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> next(
			MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext)
			throws Exception {
		return endNode;
	}
}
